package com.inossem.emergency.utils.requestUtils;

import android.app.Activity;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.inossem.emergency.constant.UrlConstant;
import com.inossem.emergency.utils.ACacheUtils;

import java.io.IOException;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Retrofit工具类
 *
 * @author 詹建宇
 * @time on 2018/11/14 16:15
 * @email jianyu.zhan@inossem.com
 */
public class RetrofitUtils {

    //请求头
    private static final String CONTENT_TYPE = "Content-Type";
    private static final String HEADER_TOKEN = "Authorization";

    public static Retrofit getRetrofit(Activity activity, String android, String java, String module, String function) {
        return new Retrofit.Builder()
                .baseUrl(UrlConstant.DEFAULT_HTTP
                        + UrlConstant.DEFAULT_DOMAIN + ":"
                        + UrlConstant.DEFAULT_PORT
                        + UrlConstant.DEFAULT_PATH)
                .client(getClient(activity, android, java, module, function))
                .addConverterFactory(GsonConverterFactory.create(getGson()))
                .build();
    }

    private static Gson getGson() {
        return new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").
                registerTypeAdapter(Date.class, GsonDateErrorAnalysis.getInstance()).create();
    }

    private static OkHttpClient getClient(Activity activity, String android, String java, String module, String function) {
        return new OkHttpClient.Builder()
                .connectTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .addInterceptor(new InossemInterceptor(activity, android, java, module, function))
                .addInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        Request request = chain.request()
                                .newBuilder()
                                .addHeader(CONTENT_TYPE, "application/json;charset=UTF-8")
                                .addHeader(HEADER_TOKEN, ACacheUtils.getToken())
                                .build();
                        return chain.proceed(request);
                    }
                })
                .build();
    }

}
